package com.panda.pandawash.activity;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.autoupdatesdk.AppUpdateInfo;
import com.baidu.autoupdatesdk.AppUpdateInfoForInstall;
import com.baidu.autoupdatesdk.BDAutoUpdateSDK;
import com.baidu.autoupdatesdk.CPCheckUpdateCallback;
import com.baidu.autoupdatesdk.CPUpdateDownloadCallback;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.panda.pandawash.R;
import com.panda.pandawash.adapter.AdapterPopWindowList;
import com.panda.pandawash.adapter.MyViewPagerAdapter;
import com.panda.pandawash.api.ApplicationConstant;
import com.panda.pandawash.application.CDApplication;
import com.panda.pandawash.bean.HttpResultBean;
import com.panda.pandawash.bean.StrongBoxBean;
import com.panda.pandawash.bean.UserBean;
import com.panda.pandawash.fragment.DeviceFragment;
import com.panda.pandawash.fragment.MarketFragment;
import com.panda.pandawash.fragment.MessageFragment;
import com.panda.pandawash.util.HttpUtil;
import com.panda.pandawash.util.ImageLoaderUtils;
import com.panda.pandawash.util.PermissionUtils;
import com.panda.pandawash.util.ProductsListUtils;
import com.panda.pandawash.view.EnterSafeDialog;
import com.panda.pandawash.view.SetSafeDialog;
import com.panda.pandawash.view.StatusBarCompat;

import org.xutils.view.annotation.ContentView;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

@ContentView(R.layout.activity_panda_wash)
public class PandaWashActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,DeviceFragment.OnFragmentInteractionListener,
        MarketFragment.OnFragmentInteractionListener,MessageFragment.OnFragmentInteractionListener,EnterSafeDialog.Builder.EnterInfoCallback {
    public static final String TAG = "API_TAG";

    private Intent intent;
    private Context context;

    private String account;
    private ImageView mAvaster;
    private TextView mPhoneNumber;

    private Toolbar toolbar;
    private ActionBar actionBar;

    private PopupWindow setPortraitWindow;
    private Uri imageUri;
    private File outputImage;

    private ImageView mPromoteImage;

    public static final int CUT_PICTURE_FROM_ALBUM = 1;
    public static final int CUT_PICTURE_FROM_CAMERA = 2;
    public static final int SHOW_PICTURE = 3;

    private String JUMPTOFORGETGACTIVITY = "com.panda.pandawash.SafeForgetPsdActivity";
    private String JUMPTOSAFEBOXACTIVITY = "com.panda.pandawash.SafeBoxActivity";

    private UserBean user;
    // 判断是否首次注册
    private Intent mIntent;

    AppUpdateInfo mInfo;
    AppUpdateInfoForInstall mInfoForInstall;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //      onAttachedToWindow();
        x.view().inject(this);
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.KITKAT) {
            StatusBarCompat.compat(this, getResources().getColor(R.color.colorPrimary));
        }

        context = getApplicationContext();
        mIntent = getIntent();
        // Toolbar
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        actionBar = this.getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        initDrawerToggle();
        showUserInfo();
        initViewPager();

        if(mIntent.getExtras()!=null && mIntent.getExtras().getBoolean("firstLogin",false)){
            showCampaignDialog();
        }

        initSharedPreference();
        SharedPreferences preferences = getSharedPreferences("update", Context.MODE_PRIVATE);
        boolean isAutoUpdate = preferences.getBoolean("is_auto_update", true);
        if (isAutoUpdate) {
            Log.d(TAG, "onCreate--auto update app version on background.");
            BDAutoUpdateSDK.cpUpdateCheck(this, new MyCPCheckUpdateCallback());
            //BDAutoUpdateSDK.silenceUpdateAction(this);
        }
    }

    private class MyCPCheckUpdateCallback implements CPCheckUpdateCallback {

        @Override
        public void onCheckUpdateCallback(AppUpdateInfo info, AppUpdateInfoForInstall infoForInstall) {
            mInfo = info;
            mInfoForInstall = infoForInstall;
            if (info != null) {
                Log.i(TAG, "install info: " + info.getAppSname() + ", \nverion="
                        + info.getAppVersionName() + ", \nchange log=" + info.getAppChangeLog());

                String prompt = "最新版本为" +info.getAppVersionName() + "，更新说明:\n"+ info.getAppChangeLog().replace("<br>", "\n") + "\n\n";
                ResultCallback mcallback = null;
                if (infoForInstall != null && !TextUtils.isEmpty(infoForInstall.getInstallPath()))
                    mcallback = new AppUpdateInstallResultCallback();
                else
                    mcallback = new AppUpdateDownloadResultCallback();
                    showConfirmDialog(PandaWashActivity.this, prompt, mcallback);
            }
        }

    }


    private interface ResultCallback {
        public void callback(boolean result);
    }

    private class AppUpdateInstallResultCallback implements ResultCallback {
        @Override
        public void callback(boolean result) {
            if (result == true){
                BDAutoUpdateSDK.cpUpdateInstall(getApplicationContext(), mInfoForInstall.getInstallPath());
            }
        }
    }

    private class AppUpdateDownloadResultCallback implements ResultCallback {
        @Override
        public void callback(boolean result) {
            if (result == true){
                BDAutoUpdateSDK.cpUpdateDownload(PandaWashActivity.this, mInfo, new UpdateDownloadCallback());
            }
        }
    }

    private class UpdateDownloadCallback implements CPUpdateDownloadCallback {

        @Override
        public void onDownloadComplete(String apkPath) {
            Log.i(TAG, "onDownloadComplete: " + apkPath);
            BDAutoUpdateSDK.cpUpdateInstall(getApplicationContext(), apkPath);
        }

        @Override
        public void onStart() {
            Log.i(TAG, "Download onStart");
        }

        @Override
        public void onPercent(int percent, long rcvLen, long fileSize) {
            Log.i(TAG, "Download onPercent: " + percent + "%");
        }

        @Override
        public void onFail(Throwable error, String content) {
            Log.i(TAG, "Download onFail: " + content);
        }

        @Override
        public void onStop() {
            Log.i(TAG, "Download onStop");
        }

    }

    public static void showConfirmDialog(Context context, String message, final ResultCallback fcCallback){
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("是否升级？").setMessage(message)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (fcCallback != null) {
                            fcCallback.callback(false);
                        }
                    }

                })
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (fcCallback != null) {
                            fcCallback.callback(true);
                        }
                    }

                });
        builder.show();
    }

    ///初次注册弹出推广框
    private void showCampaignDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(PandaWashActivity.this);
        builder.setMessage(context.getResources().getString(R.string.dialog_show_campaign_message));
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                /**
                 * 首先检测location权限是否打开
                 */
                if (PermissionUtils.isLocationEnable(PandaWashActivity.this)) {
                    requestLocationPermission();
                } else {
                    requestDialog();//手动打开
                }
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ///在侧边栏显示未推广标志，
                dialog.dismiss();
            }
        });
        builder.create().show();

    }

    private void requestDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(PandaWashActivity.this);
        builder.setTitle(getResources().getString(R.string.location_enable_title).toString());
        builder.setMessage(getResources().getString(R.string.location_enable_notification).toString());
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, 0); // 设置完成后返回到原来的界面
            }
        });
        builder.show();
    }


    private void requestLocationPermission() {
        Log.d("gwf_add", "request permission");
        if (ContextCompat.checkSelfPermission(PandaWashActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(PandaWashActivity.this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        } else {
            ///跳转推广界面
            Intent mIntent = new Intent(PandaWashActivity.this, PromoteActivity.class);
            PandaWashActivity.this.startActivity(mIntent);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    ///跳转推广界面
                    Intent mIntent = new Intent(PandaWashActivity.this, PromoteActivity.class);
                    PandaWashActivity.this.startActivity(mIntent);
                }

                break;

            case REQUEST_APP_PERMISSIONS_CREATE:
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        // permission denied
                        showMessage(getString(R.string.plate_permission_check_fail));
                        /*Toast.makeText(getApplicationContext(), R.string.plate_permission_check_fail,
                                Toast.LENGTH_SHORT).show();*/
                        return;
                    }
                }
                Intent qrcodeIntent = new Intent(PandaWashActivity.this, ScanPlateActivity.class);
                startActivity(qrcodeIntent);

                break;


            default:
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.e("gwf_add", "注册广播事件");
        // 注册自定义动态广播消息
        IntentFilter filter_dynamic = new IntentFilter();
        filter_dynamic.addAction(JUMPTOFORGETGACTIVITY);
        filter_dynamic.addAction(JUMPTOSAFEBOXACTIVITY);
        registerReceiver(myBroadcastReceiver, filter_dynamic);
    }

    private void initDrawerToggle(){
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

    }

    private void showUserInfo(){
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        View headerLayout = navigationView.getHeaderView(0);
        headerLayout.setBackground(getResources().getDrawable(R.drawable.ic_nav_head_bg));
        mAvaster = (ImageView) headerLayout.findViewById(R.id.ic_avatar);
        mAvaster.setOnClickListener(mAvasterListener);
        mPhoneNumber =(TextView) headerLayout.findViewById(R.id.phone_num);
        user = CDApplication.getIntance().getUserInfo();
        account = user.getUseraccount();
        ImageLoaderUtils.displayRound(this, mAvaster, user.getAvatar());
        mPhoneNumber.setText(account);

    }
    //导航栏头像
    @Override
    protected void onResume() {
        super.onResume();
        refreshPhotoImage();

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroadcastReceiver);
    }

    private void refreshPhotoImage() {
        Bitmap bm = PersonInfoSettingActivity.loadImageFromFile(PandaWashActivity.this);
        if (bm != null) {
            mAvaster.setImageBitmap(bm);
        }
    }
    //导航栏头像
    //用户头像点击,跳转用户设置界面
    View.OnClickListener mAvasterListener = new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            intent = new Intent(PandaWashActivity.this,PersonInfoSettingActivity.class);
            startActivity(intent);
        }
    };

    private void initViewPager(){
        ViewPager mViewPager = (ViewPager) findViewById(R.id.viewpager);
        MyViewPagerAdapter viewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.addFragment(DeviceFragment.newInstance(),getResources().getString(R.string.device_fragment_title));//添加Fragment
        viewPagerAdapter.addFragment(MarketFragment.newInstance(),getResources().getString(R.string.market_fragment_title));
        viewPagerAdapter.addFragment(MessageFragment.newInstance(),getResources().getString(R.string.message_fragment_title));
        mViewPager.setAdapter(viewPagerAdapter);//设置适配器

        TabLayout mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
        mTabLayout.addTab(mTabLayout.newTab().setText(getResources().getString(R.string.device_fragment_title)));//给TabLayout添加Tab
        mTabLayout.addTab(mTabLayout.newTab().setText(getResources().getString(R.string.market_fragment_title)));
        mTabLayout.addTab(mTabLayout.newTab().setText(getResources().getString(R.string.message_fragment_title)));
        mTabLayout.setupWithViewPager(mViewPager);

    }

    private void initSharedPreference() {

        SharedPreferences sp = getSharedPreferences("safe_box", Context.MODE_PRIVATE);

        SharedPreferences.Editor editor2 = sp.edit();
        editor2.putString("safe_box_dialog", "");
        editor2.commit();
    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.panda_wash, menu);

        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        mPromoteImage  = (ImageView) findViewById(R.id.nav_new_badge);
        if( !CDApplication.getIntance().getPreferenceUtils().getBoolean("firstLogin",true)){
            mPromoteImage.setVisibility(View.GONE);
        }else{
            mPromoteImage.setVisibility(View.VISIBLE);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_qrcode) {
            if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M) {
                if( hasDisabledPermissions()) {
                    requestPermissions(mPerms, REQUEST_APP_PERMISSIONS_CREATE);
                    return false;
                }else{
                    Intent qrcodeIntent = new Intent(PandaWashActivity.this, ScanPlateActivity.class);
                    startActivity(qrcodeIntent);
                }
            }


            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * add for all permissions
     */

    public static final int REQUEST_APP_PERMISSIONS_CREATE = 0x03;
    public static final String[] mPerms = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
    };// android M permission

    //add for android M permission
    private boolean hasDisabledPermissions() {
        final PackageManager pm = getPackageManager();
        final String packageName = getPackageName();
        for (int i = 0; i < mPerms.length; i++) {
            if (pm.checkPermission(mPerms[i], packageName)
                    != PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        }
        return false;
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_campaign) {
            intent = new Intent(PandaWashActivity.this, PromoteFeedbackActivity.class);
            startActivity(intent);
            hiddenNavigationView();
        } else if (id == R.id.nav_lockfast) {
            // 需要与服务器交互？ 修改逻辑
            Log.d(TAG, "isSettedStrongBoxPsw = ");
            isSettedStrongBoxPsw();
        } else if (id == R.id.nav_update) {
            intent = new Intent(PandaWashActivity.this,UpdateActivity.class);
            startActivity(intent);
            hiddenNavigationView();
        } else if (id == R.id.nav_servicenum) {
            intent = new Intent(PandaWashActivity.this,ServiceNoActivity.class);
            startActivity(intent);
            hiddenNavigationView();
        } else if (id == R.id.nav_quit) {
            CDApplication.getIntance().setLoginStatus(false);
            user=new UserBean();
            user.setUseraccount(account);
            user.setUserpassword(null);
            CDApplication.getIntance().saveUserInfo(user);
            finish();
        }


        return true;
    }

    private void hiddenNavigationView() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CUT_PICTURE_FROM_ALBUM:
                if (resultCode == RESULT_OK) {
                    cropImageUriFromAlbum(data.getData(), imageUri, 115, 115, SHOW_PICTURE);
                }
                break;

            case CUT_PICTURE_FROM_CAMERA:
                if (resultCode == RESULT_OK) {
                    cropImageUriFromCamera(imageUri, 115, 115, SHOW_PICTURE);
                }
                break;
            case SHOW_PICTURE:
                if (resultCode == RESULT_OK) {
                    try {
                        // 将output_image.jpg对象解析成Bitmap对象，然后设置到ImageView中显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        mAvaster.setImageBitmap(bitmap);

                        if (setPortraitWindow != null) {
                            setPortraitWindow.dismiss();
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    outputImage.delete();
                }
                break;

            default:
                break;
        }
    }

    private void cropImageUriFromCamera(Uri uri, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }

    private void cropImageUriFromAlbum(Uri uri1, Uri uri2, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri1, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }

    private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("gwf_add", "broad inner");
            if(intent.getAction().equals(JUMPTOFORGETGACTIVITY)) {
                String msg = intent.getStringExtra("msg");
                linkSafeForgetPsdActivity();
            } else if (intent.getAction().equals(JUMPTOSAFEBOXACTIVITY)) {
                String msg = intent.getStringExtra("msg");
                linkSafeBoxActivity();
            }
        }
    };

    public void linkSafeForgetPsdActivity() {
        Intent intent = new Intent(PandaWashActivity.this, SafeForgetPsdActivity.class);
        startActivity(intent);
    }

    public void linkSafeBoxActivity() {
        Intent intent = new Intent(PandaWashActivity.this, SafeBoxActivity.class);
        startActivity(intent);
    }

    /// ========= 移植 ========
    private int position = 0;
    public int getPosition() {
        return position;
    }

    private void isSettedStrongBoxPsw(){
        String useraccount = CDApplication.getIntance().getUserInfo().getUseraccount();
        HttpUtil.isSetedStrongPSW(new IsSafeBoxSettedCallback(),useraccount,useraccount);
    }

    @Override
    public void onEDialogOKbuttonClick(String password) {
        Log.d(TAG, "aaaaa password= "+password);
        loginStrongBoxPsw(password);
    }

    private class IsSafeBoxSettedCallback extends AsyncHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, String content) {
            super.onSuccess(statusCode, content);
            Log.d(TAG, "IsSafeBoxSettedCallback statusCode = " + statusCode);
            Log.d(TAG, "IsSafeBoxSettedCallback onSuccess = " + content);
            if (statusCode == 200) {
                HttpResultBean resultBean = HttpUtil.parserHttpResultInfo(content, null);
                Log.d(TAG, "resultBean = " + resultBean);
                if (resultBean != null) {
                    String code = resultBean.getCode();
                    String message = resultBean.getMessage();
                    Log.d(TAG, "code = " + code);
                    if(code.equals("0")){
                        ArrayList<Object> dataArrayList = resultBean.getData();
                        Log.d(TAG,"dataArrayList ="+dataArrayList);
                        if (dataArrayList != null) {
                            String data = (String) dataArrayList.get(0);
                            if("1".equals(data)){
                                Intent enterIntent = new Intent(PandaWashActivity.this, EnterSafeActivity.class);
                                startActivity(enterIntent);
                            }else if("0".equals(data)){
                                Intent setIntent = new Intent(PandaWashActivity.this, SetSafeActivity.class);
                                startActivity(setIntent);
                            }
                        }
                    }else if(code.equals("99")){
                        showMessage(getString(R.string.safe_box_info_get_fail));
                    }
                }

            } else {
                showMessage(getString(R.string.safe_box_info_get_fail));
            }
        }

        @Override
        public void onFailure(Throwable error, String content) {
            super.onFailure(error, content);
            Log.d(TAG, "onFailure = " + error);
            if (error.toString().contains("refused")) {
                showMessage(getString(R.string.safe_box_info_get_fail));
            }

        }
    }

    private void showMessage(String string) {
        Toast toast = Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }



    private void loginStrongBoxPsw(String password){
        String account = CDApplication.getIntance().getUserInfo().getUseraccount();
        StrongBoxBean strongBoxBean = new StrongBoxBean();
        strongBoxBean.setSecretpassword(password);
        HttpUtil.loginStrongBoxPSW(new LoginSafeBoxCallback(),account,account,strongBoxBean);
    }

    private class LoginSafeBoxCallback extends AsyncHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, String content) {
            super.onSuccess(statusCode, content);
            Log.d(TAG, "LoginSafeBoxCallback statusCode = " + statusCode);
            Log.d(TAG, "LoginSafeBoxCallback onSuccess = " + content);
            if (statusCode == 200) {
                HttpResultBean resultBean = HttpUtil.parserHttpResultInfo(content, null);
                Log.d(TAG, "resultBean = " + resultBean);
                if (resultBean != null) {
                    String code = resultBean.getCode();
                    String message = resultBean.getMessage();
                    Log.d(TAG, "code = " + code);
                    if(code.equals("0")){
                        showMessage(context.getString(R.string.safe_box_login_success));

                        Intent intent = new Intent();
                        intent.setAction(JUMPTOSAFEBOXACTIVITY);
                        intent.putExtra("msg", "发送确定进入保险箱广播成功！");
                        context.sendBroadcast(intent);

                    }else if(code.equals("99")){
                        showMessage(message);
                    }
                }
            } else {
                showMessage(context.getString(R.string.safe_box_login_fail));
            }
            //dialog.dismiss();
        }

        @Override
        public void onFailure(Throwable error, String content) {
            super.onFailure(error, content);
            Log.d(TAG, "onFailure = " + error);
            if (error.toString().contains("refused")) {

            }
            // dialog.dismiss();
        }

    }
}
